Telegram Group & Telegram Channel
🖥 Хитрая задача на Python для продвинутых: словарь, который работает как список

Представь структуру данных, которая:
• работает как dict — доступ по ключу
• работает как list — доступ по индексу
• сохраняет порядок вставки
• поддерживает .index(key) и .key_at(i)

📌 Задача: Реализуй класс IndexedDict, который делает всё это.

🔍 Пример использования:


d = IndexedDict()
d["a"] = 10
d["b"] = 20
d["c"] = 30

print(d["a"]) # 10
print(d[0]) # 10
print(d[1]) # 20
print(d.key_at(1)) # "b"
print(d.index("c")) # 2

for k in d:
print(k, d[k]) # перебор по ключам


⚠️ Подвох:

• Просто наследовать dict не получится — d[0] будет интерпретироваться как ключ, а не индекс
• Придётся реализовать двойную логику доступа вручную
• Нужно корректно поддержать __iter__, __getitem__, __len__ и др.

Решение:

```python
from collections.abc (collections.abc) import MutableMapping

class IndexedDict(MutableMapping):
def __init__(self):
self._data = {}
self._keys = []

def __getitem__(self, key):
if isinstance(key, int):
real_key = self._keys[key]
return self._data[real_key]
return self._data[key]

def __setitem__(self, key, value):
if key not in self._data:
self._keys.append(key)
self._data[key] = value

def __delitem__(self, key):
if key in self._data:
self._keys.remove(key)
del self._data[key]

def __iter__(self):
return iter(self._keys)

def __len__(self):
return len(self._data)

def index(self, key):
return self._keys.index(key)

def key_at(self, idx):
return self._keys[idx]
```

📈 Зачем это нужно:

• Отличная тренировка на переопределение магических методов
• Часто встречается в фреймворках (Pandas, SQLAlchemy)
• Тестирует знание ABC-классов (`collections.abc.MutableMapping`)
• Полезно для построения кастомных структур данных

Хочешь версию с `__contains__`, `__reversed__`, типизацией и сериализацией — пиши 💬



@Python_Community_ru



tg-me.com/Python_Community_ru/2626
Create:
Last Update:

🖥 Хитрая задача на Python для продвинутых: словарь, который работает как список

Представь структуру данных, которая:
• работает как dict — доступ по ключу
• работает как list — доступ по индексу
• сохраняет порядок вставки
• поддерживает .index(key) и .key_at(i)

📌 Задача: Реализуй класс IndexedDict, который делает всё это.

🔍 Пример использования:


d = IndexedDict()
d["a"] = 10
d["b"] = 20
d["c"] = 30

print(d["a"]) # 10
print(d[0]) # 10
print(d[1]) # 20
print(d.key_at(1)) # "b"
print(d.index("c")) # 2

for k in d:
print(k, d[k]) # перебор по ключам


⚠️ Подвох:

• Просто наследовать dict не получится — d[0] будет интерпретироваться как ключ, а не индекс
• Придётся реализовать двойную логику доступа вручную
• Нужно корректно поддержать __iter__, __getitem__, __len__ и др.

Решение:

```python
from collections.abc (collections.abc) import MutableMapping

class IndexedDict(MutableMapping):
def __init__(self):
self._data = {}
self._keys = []

def __getitem__(self, key):
if isinstance(key, int):
real_key = self._keys[key]
return self._data[real_key]
return self._data[key]

def __setitem__(self, key, value):
if key not in self._data:
self._keys.append(key)
self._data[key] = value

def __delitem__(self, key):
if key in self._data:
self._keys.remove(key)
del self._data[key]

def __iter__(self):
return iter(self._keys)

def __len__(self):
return len(self._data)

def index(self, key):
return self._keys.index(key)

def key_at(self, idx):
return self._keys[idx]
```

📈 Зачем это нужно:

• Отличная тренировка на переопределение магических методов
• Часто встречается в фреймворках (Pandas, SQLAlchemy)
• Тестирует знание ABC-классов (`collections.abc.MutableMapping`)
• Полезно для построения кастомных структур данных

Хочешь версию с `__contains__`, `__reversed__`, типизацией и сериализацией — пиши 💬



@Python_Community_ru

BY Python Community


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/Python_Community_ru/2626

View MORE
Open in Telegram


Python Community Telegram | DID YOU KNOW?

Date: |

How to Use Bitcoin?

n the U.S. people generally use Bitcoin as an alternative investment, helping diversify a portfolio apart from stocks and bonds. You can also use Bitcoin to make purchases, but the number of vendors that accept the cryptocurrency is still limited. Big companies that accept Bitcoin include Overstock, AT&T and Twitch. You may also find that some small local retailers or certain websites take Bitcoin, but you’ll have to do some digging. That said, PayPal has announced that it will enable cryptocurrency as a funding source for purchases this year, financing purchases by automatically converting crypto holdings to fiat currency for users. “They have 346 million users and they’re connected to 26 million merchants,” says Spencer Montgomery, founder of Uinta Crypto Consulting. “It’s huge.”

How Does Bitcoin Mining Work?

Bitcoin mining is the process of adding new transactions to the Bitcoin blockchain. It’s a tough job. People who choose to mine Bitcoin use a process called proof of work, deploying computers in a race to solve mathematical puzzles that verify transactions.To entice miners to keep racing to solve the puzzles and support the overall system, the Bitcoin code rewards miners with new Bitcoins. “This is how new coins are created” and new transactions are added to the blockchain, says Okoro.

Python Community from pl


Telegram Python Community
FROM USA